package com.lagou.module.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {

    public static DataSource dataSource;

    static {

        try {
            //属性集对象
            Properties p = new Properties();

            //加载配置文件
            InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");

            //通过properties 对象load 方法  从字节流 读取配置信息
            p.load(inputStream);

            //通过工厂 获取连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(p);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static Connection getConnection(){

        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

    }

    public  static DataSource getDataSource(){
        return dataSource;
    }

    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if (con != null && statement != null && resultSet != null){
            try {
                resultSet.close();
                statement.close();
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }




}
